#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include "tools.h"
#include "userdao_impl.h"
//文件加载
void UserDaoImpl::load(vector<Reader>& readers)
{
	FILE* frp = fopen("account/readers.dat","rb");
	if(frp == NULL)
	{
		return;
	}
	readers.clear();

	int money = 0;
	int id = 0;
	char name[20] = {};


	int num1 = 0;
	fread(&num1,sizeof(int),1,frp);


	for(int j=0;j<num1;j++)
	{	
		char buf[255] = {};
		Reader* reader = new Reader;
		fread(buf,sizeof(Reader),1,frp);


		sscanf(buf,"%s %d %d",name,&id,&money);
		reader->set_name(name);	
		reader->set_id(id);
		reader->set_money(money);
		reader->getvector().clear();


		int num2 = 0;
		fread(&num2,sizeof(int),1,frp);


		for(int i=0; i<num2;i++)
		{
			Book book;
			fread(&book,sizeof(Book),1,frp);
			reader->getvector().push_back(book);
		}

		int num3 = 0;
		fread(&num3,sizeof(int),1,frp);
		for(int i=0; i<num3; i++)
		{
			int id = 0; 
			fread(&id,sizeof(int),1,frp);
			reader->bookid.push_back(id);
		}
		readers.push_back(*reader);
	}
	fclose(frp);
}
//文件保存
void UserDaoImpl::save(vector<Reader>& readers)
{
	FILE* fwp = fopen("account/readers.dat","wb");
	if(fwp == NULL)
	{
		perror("fopen");
		return;
	}	
	int num1 = readers.size();
	fwrite(&num1,sizeof(num1),1,fwp);
	for(unsigned int i=0; i<readers.size(); i++)
	{
		char buf[255] = {};
		char name[20] = {};
		strcpy(name,readers[i].get_name());	
		int id = readers[i].get_id();
		int money = readers[i].get_money();
		sprintf(buf,"%s %d %d",name,id,money);
		fwrite(buf,sizeof(Reader),1,fwp);
		int num2 = readers[i].books.size();
		fwrite(&num2,sizeof(int),1,fwp);
		for(unsigned int j=0; j<readers.at(i).books.size(); j++)
		{
			fwrite(&readers[i].books[j],sizeof(Book),1,fwp);
		}
		int num3 = readers[i].bookid.size();
		fwrite(&num3,sizeof(int),1,fwp);
		for(unsigned int j=0; j<readers.at(i).bookid.size(); j++)
		{
			fwrite(&readers[i].bookid[j],sizeof(int),1,fwp);
		}
	}
	fclose(fwp);
}
